package com.gwtgeo.ui.client.mvp.layers;

import java.util.HashMap;
import java.util.Map;

import net.customware.gwt.presenter.client.EventBus;

import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.gwtgeo.ui.client.mvp.windowsmanager.WinModalDataNames;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowTypeEnum;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedDisplay;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedPresenter;
import com.gwtgeo.ui.shared.event.CloseWinModalEvent;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.HasClickHandlers;

public class AddLayerPresenter extends
		WindowedPresenter<AddLayerPresenter.Display> {

	public interface Display extends WindowedDisplay {
		HasClickHandlers getAcceptClick();

		HasClickHandlers getCancelClick();

		HasText getLayerName();

		HasText getLayerUrl();

		HasText getLayerParams();

		boolean validate();
	}

	@Inject
	public AddLayerPresenter(Display display, EventBus eventBus) {
		super(display, eventBus);
		this.init(null);
	}

	@Override
	public void init(Map<String, Object> params) {
	}

	@Override
	public WindowTypeEnum getType() {
		return WindowTypeEnum.ADD_LAYER;
	}

	@Override
	protected void onBind() {
		super.onBind();
		this.registerHandler(this.display.getAcceptClick().addClickHandler(
				new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						if (display.validate()) {
							eventBus.fireEvent(new CloseWinModalEvent(
									getType(), WindowTypeEnum.LAYERS,
									retrieveFormData()));
						}
					}
				}));
		this.registerHandler(this.display.getCancelClick().addClickHandler(
				new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						eventBus.fireEvent(new CloseWinModalEvent(getType()));
					}
				}));
	}

	private Map<String, Object> retrieveFormData() {
		Map<String, Object> data = new HashMap<String, Object>();
		data
				.put(WinModalDataNames.LAYER_NAME, display.getLayerName()
						.getText());
		data.put(WinModalDataNames.LAYER_URL, display.getLayerUrl().getText());
		data.put(WinModalDataNames.LAYER_PARAMS, display.getLayerParams()
				.getText());
		return data;
	}

	@Override
	protected void onRevealDisplay() {
	}

	@Override
	protected void onUnbind() {
	}

}
